<?php

namespace App\Model;
use OpenSearch\Client\DocumentClient;
use OpenSearch\Client\OpenSearchClient;
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;
class OpenSearch
{
    protected string $table = 'db_sou_hetong';
    protected string $accessKeyId = 'LTAI5tCMFtVBctspxvSLVjgm';
    protected string $secret = '9t5sM7TkxUPAxSvUS3Q1QdoHiXJAIM';
    protected string $endPoint = 'http://opensearch-cn-hangzhou.aliyuncs.com';
    protected string $appName = '110349061';
    protected array $options = array('debug' => true);
    protected $client;

    public function __construct()
    {
        $this->client = new OpenSearchClient($this->accessKeyId, $this->secret, $this->endPoint, $this->options);
    }

    /**阿里云-搜索
     * @param array $params
     * @return array
     */
    public function search(array $params):array{
        if(!isset($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit'])){
            $params['limit'] = 20;
        }
        $searchClient = new SearchClient($this->client);
        $paramsModel = new SearchParamsBuilder();
        $paramsModel->setStart(((int)$params['page']-1)*(int)$params['limit']);
        $paramsModel->setHits((int)$params['limit']);
        $paramsModel->setAppName($this->appName);
        $paramsModel->setQuery("default:'{$params['keyword']}'");
        $paramsModel->setFormat("fulljson");
        $ret = $searchClient->execute($paramsModel->build());
        $ret =  json_decode($ret->result,true);
        if($ret['status'] == 'OK'){
            $ret['result']['total'] = $ret['result']['total'] > 5000?5000:$ret['result']['total'];
            return $ret['result'];
        }
       return [];
    }

    /**阿里云添加文档
     * @param array $params
     * @return void
     */
    public function add(array $params,string $type='ADD'){
        $documentClient = new DocumentClient($this->client);
        //添加文档数据
        $docs_to_upload = array();
        foreach($params as $k => $v){
            $item = array();
            $item['cmd'] = $type;
            $item["fields"] = array(
                "id" => $v['id'],
                "title" => $v['title'],
                "title_pic"=>$v['title_pic']
            );
            $docs_to_upload[] = $item;
            Contract::where('id',$v['id'])->update(['is_make'=>4]);
        }
        $json = json_encode($docs_to_upload);
        $ret = $documentClient->push($json, $this->appName, $this->table);
        return $ret;
    }
}
